/**
 * 将线程设置为后台线程
 */
public class ThreadExample5 {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() + " : I am alive!");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                System.out.println(Thread.currentThread().getName() + " : I am leave in just one second!!");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "I am Daemon");


        // 设置为 后台进程
        // 这里意味着 main 方法结束后, 线程也会被结束
        thread.setDaemon(true);

        thread.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main 程序将在 1 秒后结束!");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * I am Daemon : I am alive!
 * I am Daemon : I am alive!
 * I am Daemon : I am alive!
 * main 程序将在 1 秒后结束!
 * I am Daemon : I am alive!
 */